<template>
	<u-popup v-model="showSelf" 
      mode="bottom" 
      border-radius="14" 
      :closeable="true" 
      :safe-area-inset-bottom="true"
      @close="onClose" 
    >
		<view class="bg-white spec-contain">
			<view class="spec-header row">
				<!-- #ifndef MP-ALIPAY -->
				<custom-image class="goods-img" radius="10rpx" @tap="previewImage(checkedGoods.goods_item.image)" :src="checkedGoods.goods_item.image" />
				<!-- #endif -->
				
				<!-- #ifdef MP-ALIPAY -->
				<image :src="checkedGoods.goods_item.image" style="width: 140rpx; height: 140rpx;border-radius: 22rpx;" @tap="previewImage(checkedGoods.goods_item.image)" />
				<!-- #endif -->
				
				<view class="goods-info flex1 ml20">
					<view class="ornament row">
						<price-format 
                          :first-size="46" 
                          :second-size="32" 
                          :subscript-size="32" 
                          :price="checkedGoods.period.rent" 
                          :weight="500"
                        />
                        <text class="xs">/天起</text>
					</view>
					<view class="line2 goods-name">{{goodsInfo.name}}</view>
					<view class="check-sku">已选：{{checkedGoods.goods_item.spec_value_str}}</view>
				</view>
			</view>
            <!-- 规格 -->
			<view class="spec-main">
				<scroll-view style="max-height: 600rpx;" scroll-y="true">
					<view class="spec-list">
                        <!-- 规格 -->
						<view v-for="(item, index) in goodsInfo.goods_spec" :key="index" class="spec">
							<view class="name mb20">{{ item.name }}</view>
							<view class="row wrap">
								<view v-for="(specitem, index2) in item.spec_value" :key="index2" :class="'spec-item sm ' +
								    ( checkedGoods.goods_item.spec_value_ids_arr.includes(specitem.id.toString()) ? 'checked' : '' ) + 
								    ( isDisable(specitem.id) ? 'disabled':'')" @click="choseSpecItem(index, index2,item.name)">
									{{ specitem.value }}
								</view>
							</view>
						</view>
                       
                        <!-- 租期 -->
                        <view class="spec">
                            <view class="name mb20">租期</view>
                            <view class="row wrap">
                                <view 
                                  v-for="(item, index) in goodsInfo.periods" 
                                  :key="index" 
                                  :class="'spec-item sm ' + ( item.periods_id == checkedGoods.period.periods_id ? 'checked' : '' )"
                                  @tap="chosePeriodsItem(item)">
                                    {{ item.name }}
                                </view>
                            </view>
                        </view>
					</view>
				</scroll-view>
				<view class="goods-num row-between">
					<view class="label">
						<text>租赁数量</text>
						<text class="stock">库存{{checkedGoods.goods_item.stock}}</text>
					</view>
					<u-number-box v-model="checkedGoods.goods_num" :min="1" :max="checkedGoods.goods_item.stock" :disabled="disabledNumberBox">
					</u-number-box>
				</view>
			</view>
			
			<!-- 底部按钮 -->
			<view class="btns row-between bg-white" :class="checkedGoods.goods_item.stock == 0 ? 'disabled':''">
				
				<!-- #ifndef MP-ALIPAY -->
				<button class="bg-primary br60 white btn" size="lg" @tap="onConfirm">{{ buttonTxt }}</button>
				<!-- #endif -->
				
				<!-- #ifdef MP-ALIPAY -->
				<view class="bg-primary br60 white btn alipay-btn" size="lg" @tap="onConfirm">{{ buttonTxt }}</view>
				<!-- <view v-if="showConfirm" class="bg-primary br60 white btn alipay-btn" size="lg" @tap="onClick('confirm')">确定</view> -->
				<!-- #endif -->
			</view>
		</view>
	</u-popup>
</template>

<script>
	export default {
        props: {
        	show: {
        		type: Boolean
        	},
        	goods: {
        		type: Object,
                required: true
        	},
        	buttonTxt: {
        		type: String,
        		default: "立即购买"
        	},
            showStock: {
                type: Boolean,
                default: true
            },
            disabledNumberBox: {
                type: Boolean,
                default: false
            },
        },
        
		data() {
			return {
				showSelf: false, // 是否显示自身Popup
                goodsInfo: {}, // 商品信息
				//选中的规格、租期、数量信息
				checkedGoods: {
				    goods_num: 1,
					goods_item: [],
					period: []
				}, 
				outOfStock: [], // 缺货的
				disable: [], // 不可选择的,
				
			};
		},
        
		watch: {
			// 数据初始化
			goods: {
				handler(value,oldValue) {
					if (Object.keys(value).length == Object.keys(oldValue).length) {
						return
					}
					
					this.goodsInfo = value;
					
					let goodsItem = value.goods_item || [];
					//获取库存为0的规格
					this.outOfStock = goodsItem.filter(item => item.stock == 0)
					// 找出库存不为0的规格
					const resultArr = goodsItem.filter(item => item.stock != 0)
					if (resultArr.length != 0) {
						resultArr[0].spec_value_ids_arr = resultArr[0].spec_value_ids.split(',');
						this.checkedGoods.goods_item = resultArr[0]
					} else {
						// 无法选择
						goodsItem[0].spec_value_ids_arr = []
						this.disable = goodsItem.map(item => item.spec_value_ids.split(','));
						this.checkedGoods.goods_item = goodsItem[0]
					}
					//默认选中的租期
					this.checkedGoods.period = value.periods[0]
					//默认商品数量选择为1
					this.checkedGoods.goods_num = 1
				},
				once: true
			},
			
			show(val) {
				this.showSelf = val
			},
			
			checkedGoods: {
				handler(value) {
					// 同步到父组件
					this.$emit('change', {
						detail: this.checkedGoods
					});
				},
				deep: true,
				immediate: true
			}
		},
		
		methods: {
            // 选择期数
            chosePeriodsItem(item) {
                this.checkedGoods.period = item
            },

           isDisable(e) {
				const res = this.disable.filter(item => item == e)
				if (res.length != 0) return true
				else return false
           },
           
           onClose() {
				this.$emit('close')
           },
           
           onConfirm(type) {
				let {
					checkedGoods,
					goodsNum
				} = this;
				if (this.checkedGoods.goods_item.length == 0) return this.$toast({
					title: '请选择商品规格'
				})
				if (this.checkedGoods.period.length == 0) return this.$toast({
					title: '请选择租期'
				})
				if (this.checkedGoods.goods_num <= 0) return this.$toast({
					title: '请选择商品数量'
				})
				if (this.checkedGoods.goods_item.stock == 0) return this.$toast({
					title: '当前选择库存不足'
				})
				
				this.$emit('confirm', {
					goods: {
						item_id: this.checkedGoods.goods_item.id, // 规格ID
						goods_num: this.checkedGoods.goods_num, // 数量
						periods_id: this.checkedGoods.period.periods_id, // 租期ID						
					},
				});
           },
           
           // 选择规格
           choseSpecItem(index, index2,name) {
				const id = this.goodsInfo.goods_spec[index].spec_value[index2].id.toString();
				
				// 无法选择
				const disable = this.disable.filter(item => item == id)
				if (disable.length != 0) return
			   
				let idsArr = this.checkedGoods.goods_item.spec_value_ids_arr;
				if (id == idsArr[index]) idsArr[index] = ''
				else idsArr[index] = id;
				//保存已选规格
				const spec_value_ids = idsArr.join(',');
				
				const goodsItem = this.goodsInfo.goods_item || [];
				const resultArr = goodsItem.filter(item => item.spec_value_ids == spec_value_ids)
				resultArr[0].spec_value_ids_arr = idsArr;
				this.checkedGoods.goods_item = resultArr[0]
           },
           
           // 过滤出需要进行禁用的规格
           getOutOfStockArr(arr, arr1, result = []) {
				arr.forEach(el => {
					if (el.num >= (arr1.length - 1)) {
						result.push(...el.different)
					}
				})
				return result
           },
           
           // 匹配出缺货库存和已选中对比结果
           getArrIdentical(arr1, arr2, arr = [], num = 0) {
				arr1.forEach(el => {
					arr2.forEach(el2 => {
						if (el == el2) {
							num += 1;
							arr.push(el)
						}
					})
				});
				return {
					num, //n个相同的
					different: this.getArrDifference([...new Set(arr)].map(Number), arr2.map(Number)),
					identical: [...new Set(arr)]
				}
           },
           
           // 匹配出已选择和缺库存的
           getArrResult(arr, outOfStock, result = []) {
				outOfStock.forEach(item => {
					const res = this.getArrIdentical(arr, item.spec_value_ids.split(','))
					if (res != undefined && res.length != 0) {
						result.push(res)
					}
				})
				return result
           },
           
           // 找出两个数组中参数不同的
           getArrDifference(arr1, arr2) {
				return arr1.concat(arr2).filter(function(v, i, arr) {
					return arr.indexOf(v) == arr.lastIndexOf(v);
				});
           },
           
           // 查看商品图片
           previewImage(current) {
				uni.previewImage({
					current,
					urls: [current] // 需要预览的图片http链接列表
				});
           }
		},
	};
</script>
<style lang="scss" scoped>
	.spec-contain {
		border-radius: 10rpx 10rpx 0 0;
		overflow: hidden;
		position: relative;

		.close {
			position: absolute;
			right: 10rpx;
			top: 10rpx;
		}

		.spec-header {
			padding: 30rpx;
			padding-right: 70rpx;
			align-items: flex-start;
			border: 1rpx solid #00000005;
			.goods-name {
				font-size: 32rpx;
				line-height: 40rpx;
			}
			.goods-img {
				width: 140rpx;
				height: 140rpx;
				flex: none;
				border-radius: 22rpx;
			}
		}

		.spec-main {
			.spec-list {
				padding: 30rpx 20rpx;

				.spec-item {
					line-height: 52rpx;
					padding: 0 20rpx;
					background-color: #F4F4F4;
					border-radius: 60rpx;
					margin: 0 20rpx 20rpx 0;
					border: 1px solid #F4F4F4;
				
					&.checked {
						background-color: #E8F6FF;
						color: $-color-primary;
						border-color: $-color-primary;
					}
				
					&.disabled {
						opacity: .5;
						text-decoration: line-through;
					}
				}
			}
			.goods-num {
				padding: 0 44rpx 20rpx;
				.label {
					display: flex;
					align-items: center;
				}
				.stock {
					font-size: 22rpx;
					color: #00000066;
					margin-left: 20rpx;
				}
			}
		}
		
		// 底部按钮无法选择
		.disabled {
		    opacity: 0.4;
		}
		
		.btns {
			height: 120rpx;
			padding: 0 30rpx;
			// margin-top: 80rpx;
		
			.add-cart {
				background-color: rgba(36, 163, 255, 0.1);
			}
		
			.btn {
				margin: 0 10rpx;
				flex: 1;
			}
			
			.alipay-btn {
				height: 80rpx;
				line-height: 80rpx;
				padding: 0 30rpx;
				text-align: center;
				font-size: 32rpx;
			}
		}
	}
	.check-sku{
		margin-top: 6rpx;
		font-size: 26rpx;
		font-weight: 700;
		color: #00000066;
	}
</style>
